const PropTypes = require('prop-types');
const React = require('react');
const createReactClass = require('create-react-class');
const {
    View,
    ListView,
    StyleSheet,
    Animated,
} = require('react-native');
const {
    JDTextInput,
    JDText,
    JDDevice,
    JDButton,
    JDRouter,
    JDSearchInput,
    JDScrollTop
} = require('@areslabs/jdreact-core-lib');

const Menus = createReactClass({
    displayName: 'Menus',

    contextTypes: {
        router: PropTypes.object
    },

    getInitialState() {
        this.ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => (r1 === r2)
        });
        return {
            ds: this.ds.cloneWithRows(this.props.routes),
        };
    },

    UNSAFE_componentWillReceiveProps(nextProps){
        if(this.props.routes.length !==nextProps.routes.length){
            this.setState({
                ds: this.ds.cloneWithRows(nextProps.routes)
            })
        }

    },

    scrollY: new Animated.Value(0),

    render() {
        return (
            <View style={styles.bodyPanel}>
                <ListView
                    style={styles.listView}
                    renderHeader={this._renderHeader}
                    dataSource={this.state.ds}
                    renderRow={this._renderRow}
                    removeClippedSubviews={false}
                    onScroll={(e) => {
                        this.scrollY.setValue(e.nativeEvent.contentOffset.y)
                    }}
                    ref={v => this.scrollView = v}
                />
                <JDScrollTop
                    scrollY={this.scrollY}
                    onPress={this._toTop}
                />
            </View>
        );
    },

    _toTop() {
        this.scrollView.scrollTo({
            y: 0,
            animated: true,
        })
    },

    _renderRow(rowData) {
        return (
            <JDButton onPress={ () => {
                this.context.router[`toExample-${rowData.id}`]({
                    title: rowData.title,
                });
            } } style={styles.btn}>
                {rowData.title}
            </JDButton>
        );
    },
});

const styles = StyleSheet.create({
    bodyPanel: {
        flex: 1,
        paddingTop: 10,
    },
    searchInput: {
        width: JDDevice.width - 40,
        marginHorizontal: 20
    },
    listView: {
        marginTop: JDDevice.getDpx(20),
        paddingHorizontal: JDDevice.getRpx(20),
    },
    btn: {
        marginBottom: JDDevice.getRpx(20),
    },
});

module.exports = Menus;
